/**
 *
 * 消息管理，现在消息先存在内存中，也可以存在Redis中
 *
 */

// 存储消息的仓库
const store = {};

const subjectMapping = {};
const subscriberList = [];

function addMessage(port, message) {
    if (!store[port]) {
        store[port] = [];
    }
    store[port].push(message);
}

function getSubject(port) {
    return subjectMapping[port];
}

function removeSubject(port, subscriber) {

}

/**
 * 主题
 */
class Subject {

    constructor(port) {
        this.port = port;
    }

    /**
     * 订阅
     * @param subscriber 订阅者
     */
    subscribe(subscriber) {
        if (!this.subscribers) {
            this.subscribers = [];
        }
        this.subscribers.push(subscriber);
    }

    /**
     * 取消订阅
     * @param subscriber
     */
    unsubscribe(subscriber) {
        this.subscribers = this.subscribers.filter(s => s !== subscriber);
    }

    // 通知所有订阅者
    notify(data) {
        this.subscribers.forEach(subscriber => subscriber.update(data));
    }
}

class Subscriber {
    constructor(port, callback) {
        this.port = port;
        this.callback = callback;
    }
    update(data) {
        if (this.callback) {
            this.callback(data);
        }
    }
}

module.exports = {
    getList(deviceId) {
        let res = store[deviceId];
        if (!res) {
            res = [];
            store[deviceId] = [];
        }
        return res;
    },
    addMessage: addMessage,
    subscribe: (deviceId) => {
        const subscriber = new Subscriber(deviceId);
        // 根据端口，获取主题
        let subject;
        if (subjectMapping[deviceId]) {
            subject = subjectMapping[deviceId];
        } else {
            subject = new Subject(deviceId);
            subjectMapping[deviceId] = subject;
        }
        subject.push(subject);
        subscriberList.push(subscriber);
        return subscriber;
    },
    unsubscribe: (port, subscriber) => {

    }
}